import { Lunar, Solar } from 'lunar-javascript'

export interface LunarInfo {
  lunarDay: string
  lunarMonth: string
  lunarYear: string
  festival?: string
  term?: string
  isHoliday?: boolean
}

// 农历信息缓存
const lunarCache = new Map<string, LunarInfo>()

/**
 * 获取农历信息
 */
export function getLunarInfo(date: Date): LunarInfo {
  const dateKey = date.toISOString().split('T')[0]
  
  if (lunarCache.has(dateKey)) {
    return lunarCache.get(dateKey)!
  }

  // 创建农历对象
  const lunar = Lunar.fromDate(date)

  const info: LunarInfo = {
    lunarDay: lunar.getDayInChinese(),
    lunarMonth: lunar.getMonthInChinese(),
    lunarYear: lunar.getYearInGanZhi(),
    isHoliday: false
  }

  // 获取农历节日
  const lunarFestivals = lunar.getFestivals()
  if (lunarFestivals && lunarFestivals.length > 0) {
    info.festival = lunarFestivals[0]
    info.isHoliday = true
  }

  // 获取节气
  const term = lunar.getJieQi()
  if (term) {
    info.term = term
    info.isHoliday = true
  }

  // 特殊节日处理
  const month = date.getMonth() + 1
  const day = date.getDate()
  
  // 添加重要的公历节日
  const solarHolidays: Record<string, string> = {
    '1-1': '元旦',
    '2-14': '情人节',
    '3-8': '妇女节',
    '5-1': '劳动节',
    '6-1': '儿童节',
    '10-1': '国庆节',
    '12-25': '圣诞节'
  }

  const holidayKey = `${month}-${day}`
  if (solarHolidays[holidayKey]) {
    info.festival = solarHolidays[holidayKey]
    info.isHoliday = true
  }

  // 添加农历传统节日
  const traditionalFestivals = {
    '1-1': '春节',
    '1-15': '元宵节',
    '5-5': '端午节',
    '7-7': '七夕节',
    '8-15': '中秋节',
    '9-9': '重阳节'
  }

  const lunarMonth = lunar.getMonth()
  const lunarDay = lunar.getDay()
  const traditionalKey = `${lunarMonth}-${lunarDay}`
  
  if (traditionalFestivals[traditionalKey]) {
    info.festival = traditionalFestivals[traditionalKey]
    info.isHoliday = true
  }

  lunarCache.set(dateKey, info)
  return info
}

// 清除缓存
export function clearLunarCache() {
  lunarCache.clear()
}

// 添加类型声明
declare module 'lunar-javascript' {
  interface Lunar {
    getDayInChinese(): string
    getMonthInChinese(): string
    getYearInGanZhi(): string
    getFestivals(): string[]
    getJieQi(): string | null
    getMonth(): number
    getDay(): number
  }

  namespace Lunar {
    function fromDate(date: Date): Lunar
  }

  namespace Solar {
    function fromDate(date: Date): Solar
  }
} 